#include "../include/head.h"
#include <sys/ioctl.h>

const char *plane[] = {
    "   ______                                                                               ",
    "   L,.   ',                                                                             ",
    "    \\      ',_                                                                         ",
    "     \\   @   ',                                                                        ",
    "      \\ ^~^    ',                                                                      ",
    "       \\         ',                                                                    ",
    "        \\___'____  ',_                          _..----.._                             ",
    "        [______       \"'==.I\\_____________..--\"<__\\_n@___4\\,_                      ",
    "      ,..-=T         __   ____________          \\/  \"'\" 0<==  \"'-+.._               ",
    "      I____|_____    }_>=========I>=**\"\"''==-------------==-   \" |   \"'-.,___       ",
    "    [_____,.--'\"                             \"\"--=<\"\"-----=====+==--''\"\"         ",
    "      \"\"'-=+..,,__,-----,_____                  -=* |                                 ",
    "                  |__   /-----'#------.,I_---------'\"                                  ",
    "                     \"\"\"\"'--..__         _.>                                        ",
    "                                \"\"'''''\"\"                                           "
};

void clear_screen() {
    printf("\033[H\033[J");
}

void get_terminal_size(int *rows, int *cols) {
    struct winsize w;
    ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
    *rows = w.ws_row;
    *cols = w.ws_col;
}

void print_at_position(int x, int y, const char *str, int cols) {
    int max_len = cols - x;
    if (max_len > 0) {
        printf("\033[%d;%dH%.*s", y, x, max_len, str);
        fflush(stdout);
    }
}

int plane_nc() {
    int i, j;
    int rows, cols;
    get_terminal_size(&rows, &cols);

    int start_position = -60;
    int end_position = cols;

    for (i = start_position; i < end_position; i++) {
        clear_screen();
        for (j = 0; j < sizeof(plane) / sizeof(plane[0]); j++) {
            int y_position = rows / 2 - (sizeof(plane) / sizeof(plane[0]) / 2) + j;
            if (i + strlen(plane[j]) > 0 && i < cols) {
                if (i >= 0) {
                    print_at_position(i, y_position, plane[j], cols);
                } else {
                    print_at_position(0, y_position, &plane[j][-i], cols);
                }
            }
        }
        usleep(25000);
    }

    clear_screen();
    return 0;
}